package com.ruoyi.web.ydz.util.quartz;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.web.ydz.domain.Drug;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service
public class QuartServiceImpl implements QuartzService {
    @Resource
    private Scheduler scheduler;
    private static final String DEFAULT_JOB_GROUP = "default_job_group";

    private static final String DEFAULT_TRIGGER_GROUP = "default_trigger_group";

    private static final String TRIGGER_PRE = "Trigger_";

    @Override
    public R addCronJob(String jobName, String cron, String jobClassName, String triggerName,JobDataMap jobDataMap) {
        try {
            JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
            if (scheduler.checkExists(jobKey)) {
                return R.fail("【添加定时任务】该作业已存在");
            }

            //构建job
            JobDetail job = (JobDetail) JobBuilder
                    .newJob((Class<? extends Job>) Class.forName(jobClassName))
                    .withIdentity(jobKey)
                    .usingJobData(jobDataMap)
                    .build();
            //Cron表达式定时构造器
            CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
            //构建Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + triggerName, DEFAULT_TRIGGER_GROUP))
                    .withSchedule(cronSchedule)
                    .build();
            //启动调度
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
        } catch (Exception e) {
            return R.fail("创建定任务失败，原因是：" + e.getMessage());
        }
        return R.fail("创建定时任务成功！", jobName + ",任务表达式：" + cron);
    }

    @Override
    public R updateCronJob(String jobName, String cron, String triggerName) {
        try{
            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_PRE + triggerName, DEFAULT_TRIGGER_GROUP);
            CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronSchedule).build();
            scheduler.rescheduleJob(triggerKey, trigger);
            return R.fail("更新定时任务成功！");
        }catch (Exception e){

            return R.fail("更新定时任务失败，原因为：" + e.getMessage());
        }
    }

    @Override
    public R pauseCronJob(String jobName, String triggerName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_PRE + triggerName, DEFAULT_TRIGGER_GROUP);
            JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);

            // 检查作业和触发器是否存在
            if (!scheduler.checkExists(jobKey) || !scheduler.checkExists(triggerKey)) {
                return R.fail("作业或触发器不存在");
            }

            // 暂停触发器
            scheduler.pauseTrigger(triggerKey);
            return R.fail("暂停定时任务成功！");
        } catch (Exception e) {
            return R.fail("暂停定时任务失败，原因是：" + e.getMessage());
        }

    }

    @Override
    public R resumeCronJob(String jobName, String triggerName) {
        try {
            // 构建触发器key
            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_PRE + triggerName, DEFAULT_TRIGGER_GROUP);
            // 恢复触发器
            scheduler.resumeTrigger(triggerKey);
            return R.fail("恢复定时任务成功！");
        } catch (Exception e) {
            return R.fail("恢复定时任务失败，原因是：" + e.getMessage());
        }
    }

    @Override
    public R deleteCronJob(String jobName, String jobGroup, String triggerName, String triggerGroup) {
        try {
            JobKey jobKey = JobKey.jobKey(jobName,  DEFAULT_JOB_GROUP);
            TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_PRE + triggerName, DEFAULT_TRIGGER_GROUP);

            if (!scheduler.checkExists(jobKey) ||!scheduler.checkExists(triggerKey)) {
                return R.fail("【删除定时任务】作业或触发器不存在");
            }

            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(jobKey);

            return R.fail("删除定时任务成功！", jobName);
        } catch (Exception e) {
            return R.fail("删除定时任务失败，原因为：" + e.getMessage());
        }
    }

    @Override
    public void getQuartLis() throws SchedulerException {

        for (String groupName : scheduler.getJobGroupNames()) {

            /*排除掉若依框架的定时任务GROUP*/
            if("DEFAULT".equals(groupName)){
                continue;
            }

            // 获取每个 group 中的 job key
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName));

            for (JobKey jobKey : jobKeys) {
                System.out.println("Job Key: " + jobKey);

                JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                System.out.println("Job Class: " + jobDetail.getJobClass().getName());

                // 获取关联的 triggers
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                for (Trigger trigger : triggers) {
                    System.out.println("  Trigger Key: " + trigger.getKey());

                    if (trigger instanceof CronTrigger) {
                        CronTrigger cronTrigger = (CronTrigger) trigger;
                        System.out.println("    Cron Expression: " + cronTrigger.getCronExpression());
                    }

                    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                    System.out.println("    Trigger State: " + triggerState);
                }

                System.out.println("--------------------------");
            }
        }

    }
}

